package com.qqserver.service;


import com.qqcommon.Message;
import com.qqcommon.MessageType;
import com.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 这是服务器,在监听9999端口,等待客户端的连接,并保持通信
 */
public class QQServer {
    private ServerSocket serverSocket=null;

    public QQServer(){
        //监听9999端口
        try {
            System.out.println("服务器,在监听9999端口");
            serverSocket=new ServerSocket(9999);

            while(true){
                Socket socket=serverSocket.accept();//等待客户端连接,如果没有客户端连接则会阻塞
                //得到socket关联的对象输入流
                ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
                User user=(User) ois.readObject();//读取客户端发送的User对象
                //得到socket关联的对象输出流
                ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
                //创建一个Message对象,准备回复客户端
                Message message=new Message();

                //验证
                if(user.getId().equals("李白")&&user.getPassword().equals("123456")){//验证成功
                    message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    oos.writeObject(message);

                    //创建一个线程和客服端保持通信,该线程要持有Socket对象
                    ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, user.getId());
                    serverConnectClientThread.start();//启动线程
                    //把线程对象放入到一个集合中 集中管理
                    ManageServerConnectClientThread.addServerConnectClientThread(user.getId(), serverConnectClientThread);
                }
                else{//验证失败
                    System.out.println(user.getId()+"验证失败了");
                    message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
                    oos.writeObject(message);
                    //关闭socket
                    socket.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {//如果退出了循环,说明服务器不在监听,则关闭socket
            try {
                serverSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
